<!--
 * @Author: Leo.wang wanglizhigs@163.com
 * @Date: 2024-06-04 22:12:02
 * @LastEditors: Leo.wang wanglizhigs@163.com
 * @LastEditTime: 2024-06-28 23:53:58
 * @FilePath: /chat-ai-plus/src/components/ChatHistory/ChatHistory.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <scroll-view
    class="full"
    scroll-y="true"
    :scroll-top="scrollTop"
    upper-threshold="300"
    @scrolltolower="scrollTopAction"
  >
    <div class="p_sm">
      <div class="chat-list mb_sm" v-if="archive === 0">
        <div class="py_default chat-item-primary" @click="handleClick">
          <u-icon class="icon" name="edit-pen-fill"></u-icon>
          <div class="content t_line">New chat</div>
        </div>
      </div>
      <ChatHistoryGroup
        :data="historyTopics"
        :archive="archive"
      ></ChatHistoryGroup>
    </div>
  </scroll-view>
</template>

<script lang="ts">
import { computed, defineComponent, onMounted, onUnmounted, ref, watch } from "vue";
import ChatHistoryGroup from "./ChatHistoryGroup.vue";
import useChatStore from "@/store/modules/chat";
import emitter from "@/utils/emitter";
export default defineComponent({
  name: "ChatHistory",
  props: {
    archive: {
      type: Number,
      default: 0,
    },
  },
  components: {
    ChatHistoryGroup,
  },
  setup(props) {
    const chatStore = useChatStore();
    const historyTopics = computed(() => {
      return chatStore.historyTopics;
    });

    let page = 0;
    const size = 20;
    let maxPage = 0;

    const getData = async (page: number) => {
      const response = await chatStore.getTopicList({
        archive: props.archive,
        page,
        size,
        version: chatStore.currentModel.version,
      });
      const { totalElements } = response.data;
      maxPage = Math.ceil(totalElements / size);
    };

    const scrollTopAction = () => {
      page += 1;
      if (page < maxPage) {
        getData(page);
      }
    };

    const scrollTop = ref(0);

    if (props.archive === 0) {
      emitter.on("refreshTopic", () => {
        page = 0;
        scrollTop.value = 0;

        getData(page);
      });
    }

    watch(
      () => chatStore.currentModel,
      (model) => {
        page = 0;
        scrollTop.value = 0;

        getData(page);
      }
    );

    onMounted(() => {
      chatStore.clearTopic();
      getData(page);
    });

    const handleClick = () => {
      chatStore.clearConversations();
      chatStore.setCurrentRoom();
    };
     
    onUnmounted(() => {
       emitter.off("refreshTopic", () => {
        page = 0;
        scrollTop.value = 0;
        getData(page);
      });
    })

    return {
      archive: props.archive,
      historyTopics,
      scrollTop,
      scrollTopAction,
      handleClick,
    };
  },
});
</script>

<style lang="scss" scoped>
@import "./index.scss";
</style>
